package com.hhf.rpc.core.bootstrap;

import com.hhf.rpc.core.RpcApplication;
import com.hhf.rpc.core.config.RegistryConfig;
import com.hhf.rpc.core.config.RpcConfig;
import com.hhf.rpc.core.model.ServiceMetaInfo;
import com.hhf.rpc.core.model.ServiceRegisterInfo;
import com.hhf.rpc.core.registry.LocalRegistry;
import com.hhf.rpc.core.registry.Registry;
import com.hhf.rpc.core.registry.RegistryFactory;
import com.hhf.rpc.core.server.impl.VertxTcpServer;

import java.util.List;

/**
 * @Author hhf
 * @Date 2024/10/20
 * @Description 服务提供者初始化
 */
public class ProviderBootstrap {


    public static void init(List<ServiceRegisterInfo> serviceRegisterInfoList) {


        //RPC框架初始化(配置和注册中心)
        RpcApplication.init();

        //全局配置
        final RpcConfig rpcConfig = RpcApplication.getRpcConfig();


        //注册服务
        for (ServiceRegisterInfo serviceRegisterInfo : serviceRegisterInfoList) {
            String serviceName = serviceRegisterInfo.getServiceName();
            //本地注册---存储信息,用于寻找实现类
            LocalRegistry.register(serviceName, serviceRegisterInfo.getImplClass());

            //注册中心注册---用于远程调用
            RegistryConfig registryConfig = rpcConfig.getRegistryConfig();
            Registry registry = RegistryFactory.getRegistry(registryConfig.getRegistry());
            ServiceMetaInfo serviceMetaInfo = new ServiceMetaInfo();
            serviceMetaInfo.setServiceName(serviceName);
            serviceMetaInfo.setServiceHost(rpcConfig.getServerHost());
            serviceMetaInfo.setServicePort(rpcConfig.getServerPort());
            try {
                registry.register(serviceMetaInfo);
            } catch (Exception e) {
                throw new RuntimeException(serviceName + "服务注册失败", e);
            }
        }



        //启动TCP服务器
        VertxTcpServer server = new VertxTcpServer();
        server.doStart(rpcConfig.getServerPort());

    }


}
